import Http from "../fish/net/Http";
import Global from "../Global";
import ProtocolEnums from "../enums/ProtocolEnums";
import PlatformBase from "./PlatformBase";

export default class VIVOPlatform extends PlatformBase{
    private _sdk:any;
    private _sharetime:number;
    private _sharecallback:Function;
    private _videoCallback:Function;
    private _bannerAd:any;
    private _loginCallBcak:(data:any) => void;
    private _adLastUpdateTime: number=0;
    private _insertAdTime:number=0;
    private _rewardAd: any;
    private _nativeAd: any;
    private _isNative:boolean;
    private _showVedio: boolean;
    private _pause:boolean=false;
    constructor(){
        super();
            this._sdk = window['qg'];
            this.initVideoAd();
    }

    public login(callback: (data:any) => void):void
    {
        if(callback){
            this._loginCallBcak=callback;
        }else{
            console.log("Login cb is null")
        }
        var self:any = this;
        if (this._sdk.getSystemInfoSync().platformVersionCode >= 1053) {
            this._sdk.login().then((res) => {
                if (res.data.token) {
                  // 使用token进行服务端对接
                    var param:any = {
                    platform:self.name(),
                    code:res.data.token,
                    spId:0,
                    shareId:0,
                    zoneId:Global.isiOS?2:1,
                    };
                    Http.send(ProtocolEnums.LOGIN,{param:JSON.stringify(param)},function(data:any){
                        self._loginCallBcak(data);
                    });
                }
            }, (err) => {
                self.uuid='';
                if(cc.sys.localStorage.getItem('uuid')){
                    self.uuid=cc.sys.localStorage.getItem('uuid');
                }else{
                    self.uuid="castle_"+(new Date()).valueOf();
                    cc.sys.localStorage.setItem('uuid',self.uuid);
                }              
                var param:any = {
                    platform:self.name(),
                    playerId:self.uuid,           
                    };
                    console.log("loginData:"+JSON.stringify(param));
                Http.send(ProtocolEnums.LOGIN,{param:JSON.stringify(param)},function(data:any){
                    self._loginCallBcak(data);
                });
            });
          }else{
            this._sdk.authorize({
                type: "token",
                success: function (obj) {  
                    self.getUserInfo(obj.accessToken);
                },
                fail: function (data, code) {
                    self.uuid='';
                    if(cc.sys.localStorage.getItem('uuid')){
                        self.uuid=cc.sys.localStorage.getItem('uuid');
                    }else{
                        self.uuid="castle_"+(new Date()).valueOf();
                        cc.sys.localStorage.setItem('uuid',self.uuid);
                    }              
                    var param:any = {
                        platform:self.name(),
                        playerId:self.uuid,           
                        };
                        console.log("loginData:"+JSON.stringify(param));
                    Http.send(ProtocolEnums.LOGIN,{param:JSON.stringify(param)},function(data:any){
                        self._loginCallBcak(data);
                    });
                }
            })
          } 
    }
    public getUserInfo(accessToken:string){
        let self=this;
        console.log("getUserInfo")   
        var param:any = {
            platform:self.name(),
            code:accessToken,
            };    
        this._sdk.getProfile({
            token: accessToken,
            success: function(data){    
                console.log(JSON.stringify(data)) 
                param.name=data.nickname;
                param.uid=data.openid;
                param.headUrl=data.avatar; 
                Http.send(ProtocolEnums.LOGIN,{param:JSON.stringify(param)},function(data:any){
                    self._loginCallBcak(data);
                }); 
            },
            fail: function(data, code) {
                Http.send(ProtocolEnums.LOGIN,{param:JSON.stringify(param)},function(data:any){
                    self._loginCallBcak(data);
                }); 
            }
        }) 
    }
    public share(callback: (success:boolean) => void):void
    {
        callback(true);
    }
    public watchAd(callback: (success:boolean) => void,adID:string=""):void
    {

        if (Date.now() - this._adLastUpdateTime < 60000) {
            callback(false);
            return;
        }    
        let self = this;
        self._adLastUpdateTime = Date.now();  
        self._videoCallback=callback;
        if(self._showVedio){   
            self.pauseAll();  
            self._pause=true;
            self._rewardAd.show();
        }else{
            self._adLastUpdateTime=0;
            self._videoCallback(false);
            self.resumeAll();
            self._rewardAd.load();
        }
       
    }
    
    public initVideoAd(){
        let self = this;
        if (!self._rewardAd) {
            self._rewardAd = this._sdk.createRewardedVideoAd({
                posId: 'qqqqqq'
            });

            var onshow = function () {               
                self._showVedio=true;    
            }.bind(self._rewardAd);
            self._rewardAd.onLoad(onshow);
            console.log("加载监听");
        }
        var onclose = function (res) {
            if(self._pause){
                self.resumeAll();
                self._pause=false;
            } 
            if (res && res.isEnded) {
                self._videoCallback(true);
                console.log("正常播放结束，可以下发游戏奖励");
            } else {
                self._videoCallback(false);
                console.log("播放中途退出，不下发游戏奖励");
            }
            self._rewardAd.load();
        }.bind(self._rewardAd);

        var onerror = function (err) {
            if(self._pause){
                self.resumeAll();
                self._pause=false;
            }       
            console.log("广告异常" + JSON.stringify(err));
            switch (err.errCode) {
                case -3:
                case -4:
                    // TipMgr.showTip('操作频繁，稍后重试');
                    break;
                case 108:
                    TipMgr.showTip('今日激励视频已达上线！');
                    break;
                default:
                    TipMgr.showTip("激励广告加载失败");
                    self._adLastUpdateTime=0;
                    break;
            }
            self._videoCallback(false);
            self._showVedio=false;
        }.bind(self._rewardAd);
        self._rewardAd.onError(onerror);
        self._rewardAd.onClose(onclose);
        self._rewardAd.load();
    }

    public showBannerad()
    {
        let self=this;
        if (this._bannerAd) {
            this._bannerAd.destroy();
            this._bannerAd = null;
        }
        var bannerAd = this._sdk.createBannerAd({
            posId: '111111',
            style: {} 
        })
        bannerAd.onError(function (err) {
            console.log("bannerErr+"+JSON.stringify(err))
        }.bind(this));
        bannerAd.show();
        this._bannerAd=bannerAd;
    }

    public hideBanner()
    {
        if(!this._bannerAd)return;
        this._bannerAd.destroy();
        this._bannerAd = null;
    }

    public name():string
    {
        return "VIVOGame";
    }

    public createNativeAd() {
        let randNum=Math.floor(Math.random()*100);
        if(UserModel.wave<=3||randNum>40){
            this.showBannerad();
            this._isNative=false;
            return;
        }else{
            this._isNative=true;
        }
        if (this._nativeAd) {
            this._nativeAd.destroy()
            this._nativeAd = null;
        }
        this._nativeAd =this._sdk.createNativeAd({
            posId: '1111111'
        });
        this._nativeAd.load()
        this._nativeAd.onLoad((res) => {
            this._nativeAd.reportAdShow({
                adId: res.adList[0].adId
            });
            UIMgr.dispatch(UIEnums.QGNATIVEAD,MsgEnums.NATIVE_SHOW,{
                url: res.adList[0].imgUrlList[0],
                title: res.adList[0].title,
                desc: res.adList[0].desc,
                cb: () => {
                    this._nativeAd.reportAdClick({
                        adId: res.adList[0].adId,
                    })
                }
            });
            // console.log('原生广告加载', JSON.stringify(res));
            this._nativeAd.offLoad();
            this._nativeAd.offError();

        })

        this._nativeAd.onError((err) => {
            console.log(JSON.stringify(err));
            console.log('原生广告加载失败');
            this._nativeAd.offLoad();
            this._nativeAd.offError();
            this._nativeAd.destroy();
            this._nativeAd = null;
        })
    }

    public hideNativeAd(){
        if(this._isNative){
            UIMgr.hide(UIEnums.QGNATIVEAD);
        }else{  
            this.hideBanner();
        }
       
    }

    
    public insertAd(){
        if (Date.now() - this._insertAdTime < 60000) {
            return;
        }
        let num=Math.floor(Math.random()*100);
        if(num>=20){
            return;
        }
        // showToast 上线之前一定要去掉!
        let interstitialAd = this._sdk.createInterstitialAd({
            posId:'1111111'
        });
        let adShow =  interstitialAd.show();
        let self=this;
        // 调用then和catch之前需要对show的结果做下判空处理，防止出错（如果没有判空，在平台版本为1052以及以下的手机上将会出现错误）
        adShow && adShow.then(() => {
            self._insertAdTime=Date.now();
            console.log("插屏广告展示成功");
            }).catch((err) => {
            switch (err.code) {
                case 30003:
                    console.log("新用户1天内不能曝光Banner，请将手机时间调整为1天后，退出游戏重新进入")
                    break;
                case 30009:
                    console.log("10秒内调用广告次数超过1次，10秒后再调用")
                    // setTimeout(() => {
                    //     show()
                    // }, 10000);
                    break;
                case 30002:
                    console.log("load广告失败，重新加载广告")
                    // setTimeout(() => {
                    //     retryShow()
                    // }, 10000);  
                    break;              
                default:
                    // 参考 https://minigame.vivo.com.cn/documents/#/lesson/open-ability/ad?id=广告错误码信息 对错误码做分类处理
                    console.log("插屏广告展示失败")
                    console.log(JSON.stringify(err))

                    break;
                }         
        });       
    }
    public pauseAll() { }

    public resumeAll() { }
}